#include "../include/head.h"

//初始化线程池
int init_ThreadPool(pThreadPool_t pPool, int thread_num)
{
    pPool->boot = 0;
    pPool->thread_num = thread_num;
    pPool->tidArr = (pthread_t*)calloc(thread_num, sizeof(pthread_t));
    ERROR_CHECK(pPool->tidArr, NULL, "calloc when create tidArr");
    init_TaskQueue(&pPool->taskQueue);
    return 0;
}

//启动线程池
int boot_ThreadPool(pThreadPool_t pPool)
{
    if (0 == pPool->boot) {
        for (int i = 0; i < pPool->thread_num; ++i) {
            int ret = pthread_create(pPool->tidArr + i, NULL, child_thread_handle, &pPool->taskQueue);
            THREAD_ERROR_CHECK(ret, "pthread create");
        }
        pPool->boot = 1;
    }
    return 0;
}

//关闭线程池
int close_ThreadPool(pThreadPool_t pPool) 
{
    if (1 == pPool->boot) {
        for (int i = 0; i < pPool->thread_num; ++i) {
            int ret = pthread_join(pPool->tidArr[i], NULL);
            THREAD_ERROR_CHECK(ret, "pthread join");
        }
        pPool->boot = 1;
    }
    return 0;
}

//销毁线程池资源
int destory_ThreadPool(pThreadPool_t pPool)
{
    free(pPool->tidArr);
    pPool->boot = 0;
    return 0;
}

